package com.yangye.pilog.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yangye.picommon.core.service.impl.BaseServiceImpl;
import com.yangye.picommon.model.page.PageRequest;
import com.yangye.picommon.model.page.PageResult;
import com.yangye.picommon.utils.IpUtil;
import com.yangye.picommon.utils.RequestHolder;
import com.yangye.picommon.utils.SecurityUtil;
import com.yangye.pilog.dao.SysLogMapper;
import com.yangye.pilog.domain.SysLog;
import com.yangye.pilog.service.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangye
 * @date 2019/9/23
 */
@Service
public class SysLogServiceImpl extends BaseServiceImpl<SysLogMapper, SysLog> implements SysLogService {

	@Override
	public PageResult<SysLog> findPage(SysLog entity, PageRequest pageRequest) {
		Page<SysLog> page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
		// 按照时间倒序排序
		Example example = new Example(SysLog.class);
		example.setOrderByClause("CREATE_TIME DESC");
		example.createCriteria().andEqualTo("username", entity.getUsername());
		dao.selectByExample(example);
		return new PageResult<SysLog>(page);
	}

	@Override
	public void saveLog(JoinPoint joinPoint, SysLog sysLog) {
		HttpServletRequest request = RequestHolder.getRequest();
		String ip = IpUtil.getIp(request);
		String ipFrom = IpUtil.getIpFrom(ip);
		String methodName = joinPoint.getSignature().getDeclaringTypeName() + "."
				+ joinPoint.getSignature().getName();
		String params = getParams(joinPoint);
		sysLog.setIp(ip);
		sysLog.setIpFrom(ipFrom);
		sysLog.setMethodName(methodName);
		sysLog.setUsername(getUsername(joinPoint));
		sysLog.setParam(params);
		this.add(sysLog);
	}

	private String getParams(JoinPoint joinPoint) {
		String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
		Object[] paramValues = joinPoint.getArgs();
		Map<String, String> params = new HashMap<>();
		for (int i = 0; i < paramNames.length; i++) {
			params.put(paramNames[i], JSONObject.toJSONString(paramValues[i]));
		}
		return JSONObject.toJSONString(params).replaceAll("\\\\", "");
	}

	private String getUsername(JoinPoint joinPoint) {
		// 如果是登录
		String method = joinPoint.getSignature().getName();
		if (StringUtils.equals(method, "login")) {
			// 获取用户名
			Object[] args = joinPoint.getArgs();
			JSONObject jsonObject = (JSONObject) JSON.toJSON(args[0]);
			return jsonObject.getString("username");
		}
		return SecurityUtil.getUsername();
	}
}
